import type { FormRules } from 'element-plus'
import { definePropType } from '@/utils'
import type { FormFields } from './type'

export default {
  formValue: definePropType<Record<string, any>>({
    type: Object,
    default: () => {}
  }),
  fields: definePropType<FormFields[]>(Array),
  inline: {
    type: Boolean,
    default: false
  },
  labelWidth: {
    type: String,
    default: 'auto'
  },
  isView: {
    type: Boolean,
    dfault: false
  },
  // 是否显示展开按钮  只针对搜索模式
  showExpand: {
    type: Boolean,
    default: false
  },
  // 默认展开的长度， showExpand 为 true时才有效
  spliceLength: {
    type: Number,
    default: 4
  },
  isNeat: {
    type: Boolean,
    default: false
  }
} as const

export const defaultEmits = {
  change: (val: any) => !!val,
  search: (query: any) => !!query
}

export const useFormRules = (fields: FormFields[]) => {
  const formRules: FormRules = {}

  fields.forEach((field) => {
    let validateRules: any[] = []
    if (field.required) {
      if (field.rules) {
        validateRules = field.rules
      } else {
        validateRules.push({
          required: true,
          message: `请填写${field.label}` || '内容不能为空',
          trigger: 'change'
        })
      }
    }
    // 自定义校验规则 等同 [{ validator: checkAge, trigger: 'blur' }],
    if (field.validateRules) {
      validateRules.push(...field.validateRules)
    }

    formRules[field.key] = validateRules
  })
  return formRules
}

export const setFieldKeyCol = (field: FormFields, props: any) => {
  // 搜索
  if (props.inline) {
    if (field.col && field.col.span) {
      return {
        span: field.col.span
      }
    } else {
      return {
        span: 6
      }
    }
  } else {
    if (field.col && field.col.span) {
      return {
        span: field.col.span
      }
    } else {
      return {
        span: 24
      }
    }
  }
}
